#include "socket.hh"
#include "tcp_minnow_socket.hh"

#include <cstdlib>
#include <iostream>
#include <span>
#include <string>
#include <format>

using namespace std;

void get_URL( const string& host, const string& path )
{
  CS144TCPSocket ack;//创建套接字
  std::string buf;
  ack.connect(Address(host,"http"));//连接指定的服务器地址
  //发送一个HTTP GET请求,\r\n 表示回车换行，用于分隔HTTP头部字段和消息主体
  ack.write(format("GET {} HTTP/1.1\r\n"
                      "Host: {}\r\n"
                      "Connection: close\r\n"
                      "\r\n",
                      path,
                      host));
  ack.shutdown( SHUT_WR );//关闭套接字的写端，告知服务器不会再发送更多数据，即设置连接为短连接，服务器在发送完响应后会关闭连接

  while (!ack.eof() ) {
    ack.read(buf);
    std::cout << buf;
    buf.clear();
  }
  ack.close();//关闭socket，释放资源

  //cerr << "Function called: get_URL(" << host << ", " << path << ")\n";
  //cerr << "Warning: get_URL() has not been implemented yet.\n";
}

int main( int argc, char* argv[] )
{
  try {
    if ( argc <= 0 ) {
      abort(); // For sticklers: don't try to access argv[0] if argc <= 0.
    }

    auto args = span( argv, argc );

    // The program takes two command-line arguments: the hostname and "path" part of the URL.
    // Print the usage message unless there are these two arguments (plus the program name
    // itself, so arg count = 3 in total).
    if ( argc != 3 ) {
      cerr << "Usage: " << args.front() << " HOST PATH\n";
      cerr << "\tExample: " << args.front() << " stanford.edu /class/cs144\n";
      return EXIT_FAILURE;
    }

    // Get the command-line arguments.
    const string host { args[1] };
    const string path { args[2] };

    // Call the student-written function.
    get_URL( host, path );
  } catch ( const exception& e ) {
    cerr << e.what() << "\n";
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}
